﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using QuickGet.Core.Models;

namespace QuickGet.Core.Services
{
    public class FileDownloadService : IFileDownloadService
    {
        private readonly ILogger _logger;
        private readonly IMemoryCache _cache;
        private readonly IOptions<QuickGetOptions> _options;

        public FileDownloadService(
            ILogger<FileDownloadService> logger, 
            IMemoryCache cache,
            IOptions<QuickGetOptions> options)
        {
            _logger = logger;
            _cache = cache;
            _options = options;
        }

        public Task<string?> CreateDownloadTokenAsync(string? filePath)
        {
            string? token = null;

            if(File.Exists(filePath) == false)
            {
                _logger.LogWarning("文件不存在: '{FilePath}'", filePath);
            }
            else
            {
                token = GenerateFileDownloadKey();

                _cache.Set(token, filePath, _options.Value.DownloadExpiration);

                _logger.LogDebug("添加缓存：{Key} -> {Value}, {Expiration}", token, filePath, _options.Value.DownloadExpiration);
            }


            return Task.FromResult(token);
        }

        private string GenerateFileDownloadKey() => Guid.NewGuid().ToString();

        public Task DeleteAsync(string token)
        {
            if(token.Token is not null)
            {
                _cache.Remove(token.Token);
            }

            return Task.CompletedTask;
        }

        public Task<string?> GetFilePathAsync(string token)
        {
            if(token is not null)
            {
                var path = _cache.Get<string>(token);
                return Task.FromResult(path);
            }
            return Task.FromResult(default(string));
        }

        public Task<string> GetFileDownloadUrlAsync(string? token)
        {
            return Task.FromResult($"{_options.Value.Domain ?? ""}/api/download/file?token={token}");
        }
    }
}
